const chokidar = require('chokidar');
const path = require('path');
const generateApiClient = require('./generate-api'); // 导入生成脚本

const apiDirToWatch = path.join(__dirname, '../src/main/api');

console.log(`Watching for API changes in ${apiDirToWatch}...`);

const watcher = chokidar.watch(apiDirToWatch, { ignoreInitial: true }).on('all', (event, changedPath) => {
  console.log(`API file changed: ${changedPath}. Regenerating API client...`);
  generateApiClient().catch(console.error);
});

// 优雅退出处理
const gracefulExit = () => {
  console.log('\nStopping API watcher...');
  watcher.close().then(() => {
    console.log('API watcher stopped.');
    process.exit(0);
  });
};

// 监听退出信号
process.on('SIGINT', gracefulExit); // Ctrl+C
process.on('SIGTERM', gracefulExit); // 终止信号
process.on('exit', () => {
  console.log('API watcher process exiting...');
});
